package com.syq.face.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.syq.face.MyApplication;
import com.syq.face.R;
import com.syq.face.adapter.AttendanceAdapter;
import com.syq.face.model.AttendanceInfo;
import com.syq.face.model.JsonResult;
import com.syq.face.utils.Base64Util;
import com.syq.face.utils.CalulateTwoLanLon;
import com.syq.face.utils.FileUtils;
import com.syq.face.utils.RetrofitUtil;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AttendanceFragment extends NotifiedFragment {
    public static final String TAG = "AttendanceFragment";


    private static final String ARG_PARAM1 = "param1";

    private String groupId;

    private int currentPosition = 0;

    private RecyclerView recyclerView;
    private AttendanceAdapter attendanceAdapter;
    private String attendanceId;


    public String getAttendanceId() {
        return attendanceId;
    }


    public void setAttendanceId(String attendanceId) {
        this.attendanceId = attendanceId;
    }

    public AttendanceFragment() {
    }

    public static AttendanceFragment newInstance(String param1) {
        AttendanceFragment fragment = new AttendanceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.groupId = getArguments().getString(ARG_PARAM1);
            Log.d(TAG, "onCreate: groupId:" + groupId);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: ");
        View rootView = inflater.inflate(R.layout.fragment_attendance, container, false);

        recyclerView = rootView.findViewById(R.id.fragment_attendance_rv);

        init();

        //开始获取数据
        loadData();

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();


    }

    private void init() {
        Log.d(TAG, "init: ");
        initAdapter();
        Log.d(TAG, "init end: ");
        recyclerView.setAdapter(attendanceAdapter);
    }

    private void initAdapter() {
        Log.d(TAG, "initAdapter: ");
        attendanceAdapter = new AttendanceAdapter();

        attendanceAdapter.setOnButtonClickListener(new AttendanceAdapter.AttendanceViewHolder.OnItemClickListener() {
            @Override
            public void onItemClick(int position, String attendanceId) {
                currentPosition = position;
                setAttendanceId(attendanceId);
                //startActivityForResult(FileUtils.openDocumentPicker("image/jpeg"), 0);
                startActivityForResult(FileUtils.openCamera(), 1);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d(TAG, "onActivityResult: ");
        if (requestCode == 0) {
            //满足该情况说明没有获取到数据，提前返回了
            if (data == null || data.getData() == null) {
                return;
            }
            //获取到文件的uri
            Log.d(TAG, "onActivityResult: uri:" + data.getData());
            //  testFileUpload(data.getData());
        } else if (requestCode == 1) {
            if (data == null) {
                Log.d(TAG, "onActivityResult: no data");
                return;
            }
            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
            Log.d(TAG, "onActivityResult: bitmap" + bitmap);

            File file = new File(getContext().getExternalCacheDir(), "temp.jpeg");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            try {
                outputStream.flush();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Log.d(TAG, "onActivityResult: data:" + bitmap);
            Log.d(TAG, "onActivityResult: file:" + file);
            byte[] bites = outputStream.toByteArray();
            testFileUpload(bites);
        }
    }


    private void testFileUpload(byte[] bytes) {


        //    Log.d(TAG, "onActivityResult: file:" + uploadFile.getAbsolutePath());
        //转换成上传的类
        //       MultipartBody.Part fileBody = RetrofitUtil.fileParseToMultipartBody("file", uploadFile);
        //个人需要的参数，用来指定服务器保存文件的路径 D://test/1.jpg
        //      String fileDirectory = "test";
        //   byte[]bytes= new byte[0];
//        try {
//       //     Log.d(TAG, "testFileUpload: path"+uploadFile.getAbsolutePath());
//       //     bytes = Files.readAllBytes(Paths.get(uploadFile.getAbsolutePath()));
//            Log.d(TAG, "testFileUpload: bytes"+bytes.toString());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        System.out.println(bytes);
        String image = Base64Util.encode(bytes);
        Log.d(TAG, "testFileUpload: attendanceId" + attendanceId);
        //   Log.d(TAG, "onActivityResult: fileDir:" + fileDirectory);
        RetrofitUtil.getInstance().getFaceService()
                .searchFace(MyApplication.getMyself().getToken(), image, attendanceId)
                .enqueue(new Callback<JsonResult>() {
                    @Override
                    public void onResponse(Call<JsonResult> call, Response<JsonResult> response) {
                        JsonResult body = response.body();
                        Log.d(TAG, "onResponse: body:" + new Gson().toJson(body));
                        if (body != null && body.getCode() == 200) {

                            Log.d(TAG, "onResponse: body" + "人脸检测成功");


                            getServiceLocation(attendanceId);
                //            Log.d(TAG, "onResponse: flag "+flag);

                        } else {
                            Log.d(TAG, "onResponse: body" + "人脸识别失败");
                            Toast.makeText(getContext(),"人脸不符，请重新考勤！",Toast.LENGTH_SHORT);
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonResult> call, Throwable t) {
                        Log.d(TAG, "onFailure: reason" + t.getMessage());
                    }
                });
//                .enqueue(new Callback<String>() {
//                    @Override
//                    public void onResponse(Call<String> call, Response<String> response) {
//                        // 返回值是服务器存储该文件的地址
//                        Log.d(TAG, "onResponse: " + response.body());
//                        //true -
//                        //1. 重新向服务器请求所有数据
//                        //2. 重新向服务器请求改变的数据
//                        //3. 我知道数据改变的情况，服务器也已经更新了，那我就不需要向服务器请求，直接修改本地的数据使其达成数据一致性
//
//                        attendanceAdapter.notifyItemStatusChanged(currentPosition);
//                    }
//
//                    @Override
//                    public void onFailure(Call<String> call, Throwable t) {
//                        Log.d(TAG, "onFailure: ");
//                    }
//                }
        //           );
    }


    private LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
   //         Toast.makeText(getContext(), "onLocationChanged函数被触发！", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "时间：" + location.getTime());
            Log.i(TAG, "经度：" + location.getLongitude());
            Log.i(TAG, "纬度：" + location.getLatitude());
            Log.i(TAG, "海拔：" + location.getAltitude());
        //    getServiceLocation(attendanceId);

        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub
            getMyLocation();
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }

    };
    private double mylat;
    private double mylon;
    private LocationManager locationManager;

    public void getMyLocation() {
        String serviceString = getActivity().LOCATION_SERVICE;// 获取的是位置服务
        locationManager = (LocationManager) getActivity().getSystemService(serviceString);// 调用getSystemService()方法来获取LocationManager对象
        String provider = LocationManager.GPS_PROVIDER;// 指定LocationManager的定位方法
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);// 调用getLastKnownLocation()方法获取当前的位置信息
        Log.i("Locator","location"+location);
        if (location != null){
            mylat = location.getLatitude();//获取纬度
            mylon = location.getLongitude();//获取经度
            Log.i("Locator","lat="+mylat+","+"lon"+mylon);
        }else{
            Log.i("Locator","location为空");

        }
        locationManager.requestLocationUpdates(provider, 10000, 10, locationListener);
        // 产生位置改变事件的条件设定为距离改变10米，时间间隔为2秒，设定监听位置变化

    }
    private boolean flag=false;


    private void getServiceLocation(String attendanceId) {


        RetrofitUtil.getInstance().getLocationService().getServiceLocation(
                "/fras/user/getAttendanceIpLocation/" + attendanceId, MyApplication.getMyself().getToken()
        ).enqueue(new Callback<JsonResult<com.syq.face.model.Location>>() {
            @Override
            public void onResponse(Call<JsonResult<com.syq.face.model.Location>> call, Response<JsonResult<com.syq.face.model.Location>> response) {
                JsonResult<com.syq.face.model.Location> body = response.body();
                Log.d(TAG, "onResponse: body:" + new Gson().toJson(body));
                com.syq.face.model.Location data = body.getData();
                Double serviceLat=data.getLatitude();
                Double servicelon=data.getLongitude();


                getMyLocation();

                double dis=CalulateTwoLanLon.getDistance(serviceLat,servicelon,mylat,mylon);
                Log.d(TAG, "onResponse: dis"+dis);
                if(dis<200){
                    Log.d(TAG, "onResponse: dis"+"距离大于300米");
                    handler.sendEmptyMessage(1);


                }else{
                    handler.sendEmptyMessage(2);

                }




            }

            @Override
            public void onFailure(Call<JsonResult<com.syq.face.model.Location>> call, Throwable t) {

            }
        });

    }

    //接受并且处理消息
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {

            if (message.what == 1) {
                Toast.makeText(getContext(),"考勤成功",Toast.LENGTH_SHORT).show();
                attendanceAdapter.notifyItemStatusChanged(currentPosition);


            }else {
                Toast.makeText(getContext(),"未在定位范围内",Toast.LENGTH_SHORT).show();
            }


            return true;
        }
    });



//    private void testFileUpload(Uri fileUri) {
//        //获取文件
//        File uploadFile = FileUtils.uriToFile(getContext(), fileUri, null);
//        testFileUpload(uploadFile);
//    }

    private void loadData() {
        Log.d(TAG, "loadData: ");
        Log.d(TAG, "loadData: "+MyApplication.getMyself().getToken()+"groupId:"+groupId);
        RetrofitUtil.getInstance().getUserService().getAttendances("/fras/user/getEnableAttendancesByGroup/"+groupId,MyApplication.getMyself().getToken())
                .enqueue(new Callback<JsonResult<List<AttendanceInfo>>>() {
                    @Override
                    public void onResponse(Call<JsonResult<List<AttendanceInfo>>> call, Response<JsonResult<List<AttendanceInfo>>> response) {
                        JsonResult<List<AttendanceInfo>> body = response.body();
                        Log.d(TAG, "onResponse: body:" + new Gson().toJson(body));
                        List<AttendanceInfo>data=body.getData();
//                        List<AttendanceInfo> data = new ArrayList<>();
//                        data.add(new AttendanceInfo("1", "2", "shxe", new Date(), new Date(), 2, 2, 1, "2021-11-09"));
//                        data.add(new AttendanceInfo("1", "2", "shxe", new Date(), new Date(), 2, 2, 2, "2021-11-09"));
//                        data.add(new AttendanceInfo("1", "2", "shxe", new Date(), new Date(), 2, 2, 0,"2021-11-09"));

                        attendanceAdapter.setAttendanceInfoList(data);
                        attendanceAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onFailure(Call<JsonResult<List<AttendanceInfo>>> call, Throwable t) {
                        Log.d(TAG, "onFailure: "+t.getMessage());
                        if (t instanceof Exception) {
                            Log.d(TAG, "onFailure: "+t.getMessage()+"code:"+t.getCause());

                        }
                    }
                });

    }

    @Override
    public void notifyDataReload() {
        Log.d(TAG, "notifyDataReload: ");
    }
}